package com.mindai.esper.monitor;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.SqlUtilConfig;
import com.mindai.common.component.hystrix.EnableHystrixCommand;
import com.mindai.common.component.rocketmq.EnableRocketMq;
import feign.Logger;
import feign.Request;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;

import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;

@SpringBootApplication
@ComponentScan
@MapperScan(value = {"com.mindai.esper.monitor..persistence.auto.mapper", "com.mindai.esper.monitor.persistence.ext.mapper"})
@EnableDiscoveryClient
@EnableCircuitBreaker
@EnableTransactionManagement
@EnableHystrixCommand
@EnableRocketMq
@Slf4j
public class Bootstrap {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        RestTemplate RestTemplate = new RestTemplate();
        RestTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return RestTemplate;
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    Request.Options requestOptions(ConfigurableEnvironment env) {
        int ribbonReadTimeout = env.getProperty("ribbon.ReadTimeout", int.class, 60000);
        int ribbonConnectionTimeout = env.getProperty("ribbon.ConnectTimeout", int.class, 10000);

        return new Request.Options(ribbonConnectionTimeout, ribbonReadTimeout);
    }


    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] gatewayRes = resolver.getResources("classpath:com/mindai/esper/monitor/persistence/**/*.xml");
        sqlSessionFactoryBean.setMapperLocations(gatewayRes);


        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:/config/spring-mybatis.xml"));

        //配置分页插件
        PageHelper pageHelper = new PageHelper();
        SqlUtilConfig sqlUtilConfig = new SqlUtilConfig();
        sqlUtilConfig.setDialect("mysql");
        sqlUtilConfig.setReasonable(false);
        sqlUtilConfig.setRowBoundsWithCount(true);
        sqlUtilConfig.setOffsetAsPageNum(true);

        pageHelper.setSqlUtilConfig(sqlUtilConfig);
        Interceptor[] plugins = new Interceptor[]{pageHelper};
        sqlSessionFactoryBean.setPlugins(plugins);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * Start
     */
    public static void main(String[] args) {
        SpringApplication.run(Bootstrap.class, args);
        log.info("Start Success");
    }
}
